package com.chen.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chen.common.Constants;
import com.chen.entity.MailLog;
import com.chen.entity.User;
import com.chen.service.MailLogService;
import com.chen.service.impl.UserServiceImpl;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 邮件发送定时任务
 *
 * @author chenchao
 * @date 2022/7/28 8:34
 */

//@Component
public class MailTask {

    @Resource
    private MailLogService mailLogService;


    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 邮件发送10秒执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask() {
        List<MailLog> logList = mailLogService.list(new QueryWrapper<MailLog>()
                .eq("status", 0)
                .lt("tryTime", LocalDateTime.now())
        );

        logList.forEach(mailLog -> {
//            如果重试次数超过3次，更新状态为投递失败，不再重试
            if (mailLog.getCount() >= 3) {
                mailLogService.update(new UpdateWrapper<MailLog>()
                        .set("status", 2)
                        .eq("msgId", mailLog.getMsgId()));
            }
            mailLogService.update(new UpdateWrapper<MailLog>()
                    .set("count", mailLog.getCount() + 1)
                    .set("updateTime", LocalDateTime.now())
                    .set("tryTime", LocalDateTime.now().plusMinutes(Constants.MSG_TIMEOUT))
                    .eq("msgId",mailLog.getMsgId()));
            User user = userService.getById(mailLog.getEid());
//            发送消息
            rabbitTemplate.convertAndSend(Constants.MMAIL_EXCHANGE_NAME,Constants.MMAIL_ROUTING_KEY_NAME,user,new CorrelationData(mailLog.getMsgId()));
        });
    }
}
